package com.mall.order.mq.promo;

import com.alibaba.fastjson.JSON;
import com.mall.order.OrderPromoService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CreateSeckillOrderRequest;
import com.mall.order.dto.CreateSeckillOrderResponse;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author : xfeng
 * @time : 2021/8/31 22:12
 * @program: myproject3
 * @description:
 */
@Component
public class CreatePromoOrderConsumer {

    private DefaultMQPushConsumer consumer;

    @Autowired
    private OrderPromoService orderPromoService;

    @PostConstruct
    public void init(){
        consumer = new DefaultMQPushConsumer("promo_order_consumer");

        consumer.setNamesrvAddr("127.0.0.1:9876");

        try {
            consumer.subscribe("create_promo_order","*");
        } catch (MQClientException e) {
            e.printStackTrace();
        }

        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt messageExt = list.get(0);
                byte[] body = messageExt.getBody();
                String s = new String(body, 0, body.length, Charset.forName("utf-8"));

                CreateSeckillOrderRequest request = JSON.parseObject(s, CreateSeckillOrderRequest.class);

                CreateSeckillOrderResponse response = orderPromoService.createPromoOrder(request);

                if(OrderRetCode.SUCCESS.getCode().equals(response.getCode())){
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }

                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });

        try {
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }


}
